package org.glut.saltedfish.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.glut.saltedfish.domain.Order;
import org.glut.saltedfish.mapper.OrderMapper;
import org.glut.saltedfish.utils.MybatisUtil;

import java.util.List;


/**
 * <p>
 * 订单实现类
 * </p>
 *
 * @author mjl
 * @since 2025/7/16
 */
public class OrderServiceImpl {
    static Logger logger = Logger.getLogger(OrderServiceImpl.class);
    /**
     * 根据条件查询订单
     * @param order 订单查询条件
     * @return 符合条件的订单列表
     */
    public List<Order> selectByCondition(Order order) {
        try (SqlSession sqlSession = MybatisUtil.getSession()) {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            return mapper.selectByCondition(order);
        } catch (Exception e) {
            logger.error("根据条件查询订单信息失败", e);
        }
        return null;
    }

    public Integer countByCondition(Order order) {
        try (SqlSession sqlSession = MybatisUtil.getSession()) {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            return mapper.countByCondition(order);
        } catch (Exception e) {
            logger.error("统计订单数量失败", e);
        }
        return 0;
    }



    /**
     * 创建订单
     * @param order 订单信息
     * @return 是否创建成功
     */
    public boolean createOrder(Order order) {
        try (SqlSession sqlSession = MybatisUtil.getSession()) {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            int result = mapper.insert(order);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            logger.error("创建订单失败", e);
            return false;
        }
    }

    /**
     * 更新订单
     * @param order 订单信息
     * @return 是否更新成功
     */
    public boolean updateOrder(Order order) {
        try (SqlSession sqlSession = MybatisUtil.getSession()) {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            int result = mapper.updateById(order);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            logger.error("更新订单失败", e);
            return false;
        }
    }
    /**
     * 删除订单
     * @param id 订单id
     * @return 是否删除成功
     */
    public boolean deleteOrder(Integer id) {
        try (SqlSession sqlSession = MybatisUtil.getSession()) {
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
            int result = mapper.deleteById(id);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            logger.error("删除订单失败", e);
            return false;
        }
    }
}
